package com.cmccgz.udacs_landlord_webapp.main.warning.view;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cmccgz.baselibrary.base.BaseFragment;
import com.cmccgz.baselibrary.utils.ScreenUtils;
import com.cmccgz.baselibrary.utils.StringUtils;
import com.cmccgz.baselibrary.utils.ToastUtils;
import com.cmccgz.baselibrary.view.MyGridView;
import com.cmccgz.baselibrary.view.adapter.BoxingAdapter;
import com.cmccgz.udacs_landlord_webapp.R;
import com.cmccgz.udacs_landlord_webapp.bean.DeviceInfoBean;
import com.cmccgz.udacs_landlord_webapp.bean.Media;
import com.cmccgz.udacs_landlord_webapp.bean.WarningDetail;
import com.cmccgz.udacs_landlord_webapp.main.device.view.SelectDevicesActivity;
import com.cmccgz.udacs_landlord_webapp.main.warning.WarningActivity;
import com.cmccgz.udacs_landlord_webapp.main.warning.contracts.WarningEditContract;
import com.cmccgz.udacs_landlord_webapp.main.warning.presenters.WarningEditPresenter;
import com.cmccgz.udacs_landlord_webapp.utils.ViewHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * 报障编辑以及提单
 *
 * @author INX
 *
 */
public class WarningEditFragment extends BaseFragment implements View.OnClickListener, WarningEditContract.View {
    private LinearLayout ll_d_name;
    private EditText et_warning_desc;
    private TextView tv_word_count;
    private MyGridView gv_desc;
    private WarningActivity parentActivity;
    private WarningEditPresenter presenter;
    private List<String> urls = new ArrayList<>();
//    private PhotoAdapter photoAdapter;
    private BoxingAdapter photoAdapter;
    private static final int REQ_SEL_DEVICE = 101;
    private DeviceInfoBean currentDevice;
    private TextView tv_device_name;
    private WarningDetail warningDetail;
    private int mode;
    public final static int MODE_ADD=0x1;
    public final static int MODE_EDIT=0x2;
    public final static int MODE_REJECT=0x3;
    private ViewHelper instance;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_warning_edit;
    }

    @Override
    protected void initView() {
        parentActivity = ((WarningActivity) getActivity());
        instance = ViewHelper.instance(this);
        instance.setBackTextVisable(true);
        instance.setTextRightVisable(true);
        instance.setRightText("完成");
        instance.setTitle("设备报障");

        ll_d_name = ((LinearLayout) findViewById(R.id.ll_d_name));
        et_warning_desc = ((EditText) findViewById(R.id.et_warning_desc));
        tv_word_count = ((TextView) findViewById(R.id.tv_word_count));
        gv_desc = ((MyGridView) findViewById(R.id.gv_desc));
        gv_desc.setNumColumns(4);
        photoAdapter = new BoxingAdapter(true, gv_desc, urls, ScreenUtils.getScreenWidth(mContext) - ScreenUtils.dpToPxInt(mContext, 32),this, 4);
//        photoAdapter = new PhotoAdapter(true, gv_desc, urls, ScreenUtils.getScreenWidth(mContext) - ScreenUtils.dpToPxInt(mContext, 32), this, 4);
        gv_desc.setAdapter(photoAdapter);
        ll_d_name.setOnClickListener(this);
        tv_device_name = ((TextView) findViewById(R.id.tv_device_name));
        et_warning_desc.addTextChangedListener(new TextWatcher() {

            private int max_count = 140;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                int length = s.length();
                if (length > max_count) {
                    showToast("输入字数不能超过" + max_count + "！");
                    et_warning_desc.setText(s.subSequence(0, max_count - 1));
                    et_warning_desc.setSelection(max_count);
                }
                tv_word_count.setText(length + "/" + max_count);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        presenter = new WarningEditPresenter(this);
        initData();
    }

    private void initData() {
        Bundle arguments = getArguments();
        if (arguments==null) {
            return;
        }
        mode = arguments.getInt("mode",MODE_ADD);
        warningDetail = ((WarningDetail) arguments.getSerializable("WarningDetail"));
        currentDevice= (DeviceInfoBean) arguments.getSerializable("device");
        if (warningDetail!=null) {
            if (currentDevice==null) {
                currentDevice=new DeviceInfoBean();
                currentDevice.device_id=warningDetail.device_id;
                currentDevice.device_name=warningDetail.device_name;
                currentDevice.house_name=warningDetail.house_name;
            }
            et_warning_desc.setText(warningDetail.desc);
            for (int i = 0; warningDetail.media!=null&&i < warningDetail.media.size(); i++) {
                Media media=warningDetail.media.get(i);
                urls.add(media.getImagePath());
            }
            photoAdapter.notifyDataSetChanged();
        }
        switch (mode) {
            case MODE_ADD:
                instance.setTitle("设备报障");
                break;
            case MODE_EDIT:
                tv_device_name.setTextColor(ContextCompat.getColor(mContext,R.color.gray_d));
                instance.setTitle("修改报障");
                break;
            case MODE_REJECT:
                tv_device_name.setTextColor(ContextCompat.getColor(mContext,R.color.gray_d));
                instance.setTitle("否决回单");
                break;
        }
        asyDeviceName();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back:
                parentActivity.onBackPressed();
                break;
            case R.id.tv_right:
                showLoadingDialog("正在提交...");
                switch (mode) {
                    case MODE_ADD:
                        presenter.waringAdd(currentDevice.device_id, et_warning_desc.getText().toString(), photoAdapter.getSelectUrls());
                        break;
                    case MODE_EDIT:
                        presenter.waringEdit(warningDetail.w_id, currentDevice.device_id, et_warning_desc.getText().toString(), photoAdapter.getSelectUrls());
                        break;
                    case MODE_REJECT:
                        presenter.waringReject(warningDetail.w_id, currentDevice.device_id, et_warning_desc.getText().toString(), photoAdapter.getSelectUrls());
                        break;
                    default:
                        dismissLoadingDialog();
                        break;
                }
                break;
            case R.id.ll_d_name:
                if (mode!=MODE_ADD) {
                    ToastUtils.show(mContext,"当前场景，无法修改设备！");
                    return;
                }
//                startActivityForResult(new Intent(mContext, SelectDevicesActivity.class), REQ_SEL_DEVICE);
                parentActivity.selectDevices();
                break;
        }
    }

    public void refreshDetail() {
        root.postDelayed(new Runnable() {
            @Override
            public void run() {
                parentActivity.refreshDetail();
            }
        },100);
    }

    @Override
    public void warningRejectSuccess() {
        dismissLoadingDialog();
        ToastUtils.show(mContext,"否决成功！");
        parentActivity.onBackPressed();
        refreshDetail();
        parentActivity.refreshWarningList();
    }


    @Override
    public void warningEditSuccess() {
        dismissLoadingDialog();
        ToastUtils.show(mContext,"修改成功！");
        parentActivity.onBackPressed();
        refreshDetail();
        parentActivity.refreshWarningList();
    }

    @Override
    public void warningAddSuccess() {
        dismissLoadingDialog();
        ToastUtils.show(mContext,"报障成功！");
        parentActivity.onBackPressed();
        parentActivity.refreshWarningList();
    }

    @Override
    public void warningRejectError(String msg) {
        dismissLoadingDialog();
        showToast(msg);
    }

    @Override
    public void warningEditError(String msg) {
        dismissLoadingDialog();
        showToast(msg);
    }

    @Override
    public void warningAddError(String msg) {
        dismissLoadingDialog();
        showToast(msg);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      /*  if (photoAdapter != null) {
            photoAdapter.onCreate(savedInstanceState);
        }*/
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_SEL_DEVICE&&resultCode== Activity.RESULT_OK) {
            currentDevice = ((DeviceInfoBean) data.getSerializableExtra(SelectDevicesActivity.KEY_RESULT_DEVICE));
            asyDeviceName();
        } else if (photoAdapter != null) {
            photoAdapter.onActivityResult(requestCode, resultCode, data);
        }
    }

    public void asyDeviceName() {
        if (currentDevice!=null
                && !StringUtils.isEmpty(currentDevice.device_id)) {
            tv_device_name.setText(StringUtils.isEmpty(currentDevice.device_name)?"未知设备":currentDevice.device_name);
        }else{
            tv_device_name.setText("");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        /*if (photoAdapter != null) {
            photoAdapter.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }*/
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
      /*  if (photoAdapter != null) {
            photoAdapter.onSaveInstanceState(outState);
        }*/
        super.onSaveInstanceState(outState);
    }

    public void setDevice(DeviceInfoBean device){
        currentDevice=device;
        asyDeviceName();
    }
}
